package health.lm.com.home.activity;

import android.annotation.SuppressLint;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.StringUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener;
import com.shuyu.gsyvideoplayer.utils.CommonUtil;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.utils.GSYVideoHelper;
import com.shuyu.gsyvideoplayer.video.NormalGSYVideoPlayer;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import health.lm.com.component_base.base.mvp.activity.XListActivity;
import health.lm.com.component_base.widget.SuperDividerItemDecoration;
import health.lm.com.data.App;
import health.lm.com.home.R;
import health.lm.com.home.R2;
import health.lm.com.home.adapter.ContentItemAdapter;
import health.lm.com.home.adapter.InformationSearchAdapter;
import health.lm.com.home.entity.ContentItemEntity;
import health.lm.com.home.presenter.InformationsSearchPresenter;
import health.lm.com.router.ARouterConstant;

/**
 * @author GQI
 * @description 资讯搜索
 * @date :2019-08-01 8:39
 */
@Route(path = ARouterConstant.InformationsSearchActivity)
public class InformationsSearchActivity extends XListActivity<InformationsSearchPresenter> {
    @BindView(R2.id.iv_back)
    ImageView ivBack;
    @BindView(R2.id.et_search)
    EditText etSearch;
    @BindView(R2.id.rv_list)
    RecyclerView rvList;
    @BindView(R2.id.srl_layout)
    SmartRefreshLayout srlLayout;
    @BindView(R2.id.fl_info_video)
    FrameLayout videoFullContainer;

    private InformationSearchAdapter itemAdapter;
    private List<ContentItemEntity> itemEntities;

    private String keyword = "";
    GSYVideoHelper.GSYVideoHelperBuilder gsySmallVideoHelperBuilder;
    GSYVideoHelper smallVideoHelper;
    int lastVisibleItem;
    int firstVisibleItem;
    private LinearLayoutManager linearLayoutManager;

    @Override
    public int getLayoutId() {
        return R.layout.activity_information_search;
    }

    @Override
    public InformationsSearchPresenter newP() {
        return new InformationsSearchPresenter();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        ivBack.setOnClickListener(v -> finish());
        initView();
        initRx();
        super.rlRefreshLayout = srlLayout;
        super.recyclerView = rvList;
        super.adapter = itemAdapter;
        super.isRefresh = false;
        super.initData(savedInstanceState);
    }

    @SuppressLint("CheckResult")
    private void initRx() {
        RxTextView.textChanges(etSearch)
                .debounce(500, TimeUnit.MILLISECONDS)
                .compose(bindToLife())
                .subscribe(charSequence -> {
                    page = 1;
                    keyword = charSequence.toString();
                    if(!StringUtils.isEmpty(keyword)){
                        getP().getListData(keyword, isRefresh, rlRefreshLayout, page, pageSize);
                    }

                });
    }

    @Override
    public void loadListData(boolean isRefresh, Object layout, int page, int pageSize) {
        if(!StringUtils.isEmpty(keyword)) {
            getP().getListData(keyword, isRefresh, layout, page, pageSize);
        }else {
            if(isRefresh){
                ((SmartRefreshLayout)layout).finishRefresh(true);
                itemAdapter.setNewData(new ArrayList<>());
            }
        }

    }

    /**
     * @author GQI
     * 初始化布局结构
     * @date :2019-06-13 14:40
     */
    private void initView() {
        itemEntities = new ArrayList<>();
        linearLayoutManager = new LinearLayoutManager(context);
        rvList.setLayoutManager(linearLayoutManager);
        itemAdapter = new InformationSearchAdapter(itemEntities, getP());
        rvList.addItemDecoration(new SuperDividerItemDecoration(new SuperDividerItemDecoration.Builder(context)
                .setDividerColor(0xffdddddd)
                .setOrientation(RecyclerView.VERTICAL)
                .setIsShowLastDivide(false)));
        rvList.setAdapter(adapter);
        itemAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ContentItemEntity itemEntity = itemEntities.get(position);
                if (ContentItemEntity.IMAGE_TEXT == itemEntity.getShow_type()) {
                    withValueActivity(ARouterConstant.InformationActivity).withString(ARouterConstant.INFO_ID, itemEntity.getNews_id()).navigation();
                }
            }
        });
        initVideo();
    }

    /**
     * 初始化video
     */
    private void initVideo() {
        smallVideoHelper = new GSYVideoHelper(context, new NormalGSYVideoPlayer(context));
        smallVideoHelper.setFullViewContainer(videoFullContainer);
        //配置
        gsySmallVideoHelperBuilder = new GSYVideoHelper.GSYVideoHelperBuilder();
        gsySmallVideoHelperBuilder
                .setHideActionBar(true)
                .setHideStatusBar(true)
                .setNeedLockFull(true)
                .setCacheWithPlay(true)
                .setAutoFullWithSize(true)
                .setShowFullAnimation(true)
                .setLockLand(true).setVideoAllCallBack(new GSYSampleCallBack() {
            @Override
            public void onPrepared(String url, Object... objects) {
                super.onPrepared(url, objects);
                //Debuger.printfLog("Duration " + smallVideoHelper.getGsyVideoPlayer().getDuration() + " CurrentPosition " + smallVideoHelper.getGsyVideoPlayer().getCurrentPositionWhenPlaying());
            }

            @Override
            public void onQuitSmallWidget(String url, Object... objects) {
                super.onQuitSmallWidget(url, objects);
                //大于0说明有播放,//对应的播放列表TAG
                if (smallVideoHelper.getPlayPosition() >= 0 && smallVideoHelper.getPlayTAG().equals(ContentItemAdapter.TAG)) {
                    //当前播放的位置
                    int position = smallVideoHelper.getPlayPosition();
                    //不可视的是时候
                    if ((position < firstVisibleItem || position > lastVisibleItem)) {
                        //释放掉视频
                        smallVideoHelper.releaseVideoPlayer();
                        itemAdapter.notifyDataSetChanged();
                    }
                }

            }
        }).setGSYVideoProgressListener(new GSYVideoProgressListener() {
            @Override
            public void onProgress(int progress, int secProgress, int currentPosition, int duration) {
                if (!App.getModel().isNeed_login()) {
                    if (StringUtils.equals("1", itemEntities.get(itemAdapter.videoPos()).getCan_reward())) {
                        if (progress == 50) {
                            getP().getSugar(rvList, String.valueOf(itemAdapter.videoPos()));
                        }
                    }
                }
            }
        });

        smallVideoHelper.setGsyVideoOptionBuilder(gsySmallVideoHelperBuilder);
        itemAdapter.setVideoHelper(smallVideoHelper, gsySmallVideoHelperBuilder);

        rvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition();
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                //Debuger.printfLog("firstVisibleItem " + firstVisibleItem + " lastVisibleItem " + lastVisibleItem);
                //大于0说明有播放,//对应的播放列表TAG
                if (smallVideoHelper.getPlayPosition() >= 0 && smallVideoHelper.getPlayTAG().equals(InformationSearchAdapter.TAG)) {
                    //当前播放的位置
                    int position = smallVideoHelper.getPlayPosition();
                    //不可视的是时候
                    if ((position < firstVisibleItem || position > lastVisibleItem)) {
                        //如果是小窗口就不需要处理
                        if (!smallVideoHelper.isSmall() && !smallVideoHelper.isFull()) {
                            //小窗口
                            int size = CommonUtil.dip2px(context, 150);
                            //actionbar为true才不会掉下面去
                            smallVideoHelper.showSmallVideo(new Point(size, size), true, true);
                        }
                    } else {
                        if (smallVideoHelper.isSmall()) {
                            smallVideoHelper.smallVideoToNormal();
                        }
                    }
                }
            }
        });
    }
    /**
     * 获取返回数据
     * @param dataList
     */
    public void getListDataSuccess(List<ContentItemEntity> dataList) {
        this.itemEntities = dataList;
        if(itemEntities.size()>=pageSize){
            initLoadMore();
        }
        if(isRefresh){
            itemAdapter.setNewData(itemEntities);
        }else {
            itemAdapter.setNewData(itemEntities);
//            itemAdapter.addData(itemEntities);
        }
        if (itemEntities.size()<pageSize){
            itemAdapter.loadMoreEnd();
        }else {
            itemAdapter.loadMoreComplete();
        }

    }
    @Override
    protected void onResume() {
        super.onResume();
        rvList.setAdapter(adapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (smallVideoHelper != null) {
            smallVideoHelper.releaseVideoPlayer();
        }
        GSYVideoManager.releaseAllVideos();
    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseVideo();
    }
    @Override
    public void onBackPressed() {
        if (smallVideoHelper.backFromFull()) {
            return;
        }
        super.onBackPressed();
    }
    private void releaseVideo() {
        if (smallVideoHelper != null) {
            smallVideoHelper.releaseVideoPlayer();
        }
        GSYVideoManager.releaseAllVideos();
        if (itemAdapter != null) {
            itemAdapter.notifyDataSetChanged();
        }
    }

}
